import type { ConfigEnv, UserConfig } from 'vite'
import { loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { viteMockServe } from 'vite-plugin-mock'
import { wrapperEnv } from './build/utils'
import { resolve } from 'path'

/** @type {import('vite').UserConfig} */
export default ({ command, mode }: ConfigEnv): UserConfig => {
  const root = process.cwd()
  const isBuild = command === 'build'
  const env = loadEnv(mode, root)
  const viteEnv: any = wrapperEnv(env)
  const { VITE_PORT, VITE_DROP_CONSOLE } = viteEnv

  return {
    base: './',
    server: {
      host: '0.0.0.0',
      open: true,
      cors: true,
      port: VITE_PORT,
      proxy: {
        '/api': {
          // target: "https://mock.mengxuegu.com/mock/62abda3212c1416424630a45",
          target: 'http://op14-ioc.whaiot.top:7001',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, '')
        }
      }
    },
    plugins: [
      react(),
      createSvgIconsPlugin({
        iconDirs: [resolve(process.cwd(), 'src/assets/icons')],
        symbolId: 'icon-[dir]-[name]'
      })
      // viteMockServe({
      //   mockPath: 'mock',
      //   ignore: /^_/,
      //   localEnabled: !isBuild,
      //   prodEnabled: isBuild,
      //   injectCode: `
      //     import { setupProdMockServer } from 'mock/_createProductionServer';
      //     setupProdMockServer()
      //     `
      // })
    ],
    build: {
      target: 'es2015',
      cssTarget: 'chrome86',
      minify: 'terser',
      terserOptions: {
        compress: {
          keep_infinity: true,
          drop_console: VITE_DROP_CONSOLE
        }
      },
      chunkSizeWarningLimit: 2000
    },
    resolve: {
      alias: {
        '@': resolve(__dirname, './src')
      }
    }
  }
}
